import Vue from 'vue'
import Vuex from 'vuex'
import $XEUtils from 'xe-utils'

Vue.use(Vuex)

import vuePer from 'vuex-persistedstate'
import SecureLS from 'secure-ls'

let plugins = [];

if (process.env.NODE_ENV === 'production') {
  const ls = new SecureLS({
    encodingType: "aes",
    isCompression: false,
    encryptionSecret: "ff_cloud"
  });
  plugins = [
    vuePer({
      key: 'ffCloud',
      storage: {
        getItem: key => ls.get(key),
        setItem: (key, value) => ls.set(key, value),
        removeItem: key => ls.remove(key)
      }
    })
  ]
} else {
  plugins = [
    vuePer()
  ]
}


export default new Vuex.Store({
  state: {
    Authentication: {
      jti: '',
      access_token: '',
      token_type: '',
      refresh_token: '',
      expires_in: 0,
      expires_time: 0,
      uid: '',
      virtualName: '',
    }
  },
  mutations: {
    setAuthentication(state, data) {
      let authentication = state.Authentication;
      authentication.access_token = data.token_type + ' ' + data.access_token;
      authentication.token_type = data.token_type;
      authentication.refresh_token = data.refresh_token;
      authentication.expires_in = data.expires_in;
      authentication.expires_time = $XEUtils.floor($XEUtils.now() / 1000, 0) + data.expires_in;
      authentication.uid = data.uid;
      authentication.virtualName = data.virtualName;
    },
    removeAuthentication(state) {
      state.Authentication = {
        jti: '',
        access_token: '',
        token_type: '',
        refresh_token: '',
        expires_in: 0,
        expires_time: 0,
        uid: '',
        virtualName: '',
      }
    }
  },
  actions: {},
  modules: {},
  plugins: plugins
})
